package com.kk.crowd.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kk.crowd.entity.Role;
import com.kk.crowd.entity.RoleExample;
import com.kk.crowd.mapper.RoleMapper;
import com.kk.crowd.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageInfo<Role> getPageInfo(Integer pageNum, Integer pageSize, String keyword) {
        // 1.开启分页功能
        PageHelper.startPage (pageNum, pageSize);

        // 2.执行查询
        List<Role> roles = roleMapper.selectRoleByKeyword (keyword);

        // 3.封装为 PageInfo 对象返回
        return new PageInfo<> (roles);
    }

    @Override
    public void saveRole(Role role) {
        roleMapper.insert (role);
    }

    @Override
    public void updateRole(Role role) {
        // “Selective”表示有选择的更新，对于null值的字段不更新
        //  updateByPrimaryKey可能造成空值覆盖（看mapping.xml得出结论）
        roleMapper.updateByPrimaryKey (role);
    }

    @Override
    public void removeRole(List<Integer> roleIdList) {
        RoleExample roleExample = new RoleExample ( );
        RoleExample.Criteria criteria = roleExample.createCriteria ( );

        // delete from t_role where id in (4,12,16)
        criteria.andIdIn (roleIdList);

        roleMapper.deleteByExample (roleExample);
    }

    @Override
    public List<Role> getAssignedRole(Integer adminId) {
        return roleMapper.selectAssignedRole (adminId);
    }

    @Override
    public List<Role> getUnAssignedRole(Integer adminId) {
        return roleMapper.selectUnAssignedRole (adminId);
    }

    @Override
    public void saveAdminRole(Map<String, List<Integer>> map) {
        // 1.获取 adminId 的值
        List<Integer> adminIdList = map.get ("adminId");
        Integer adminId = adminIdList.get (0);

        // 2.删除旧关联关系数据
        roleMapper.deleteOlAdmin (adminId);

        // 3.获取 roleIdList
        List<Integer> roleIdList = map.get ("roleIdList");
        if (roleIdList != null && roleIdList.size ( ) > 0) {
            roleMapper.insertNewAdmin (adminId, roleIdList);
        }
    }
}
